package com.jige.jigetodo.model.timer;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.time.LocalDateTime;

@Component
public class TaskStatusScheduler {

    @PersistenceContext
    private EntityManager entityManager;

    @Scheduled(fixedRate = 60 * 1000)  // 每分钟执行一次
    @Transactional
    public void updateExpiredTasks() {
        // 使用原生SQL查询（确保表名和字段名与数据库一致）
        String sql = "UPDATE task " +
                "SET status = 2, updateTime = NOW() " +
                "WHERE status = 0 " +
                "AND deadTime < NOW() " +
                "AND isDelete = 0";

        int updatedCount = entityManager.createNativeQuery(sql)
                .executeUpdate();

        if (updatedCount > 0) {
            System.out.println("成功更新 " + updatedCount + " 个过期任务");
        }
    }
}